package com.smit.update.service;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.smit.update.activity.UpdateActivity;
import com.smit.utils.SharePrefUtil;

import java.io.File;

public class BootBroadcastReceiver extends BroadcastReceiver {
    final String TAG = "BootBroadcastReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Log.d("BootBroadcastReceiver", action);
        if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
            //检测是否有升级包，如果有直接强制升级，否则，进入后台
            if (!autoUpdateCheck(context)) {
                Intent serviceIntent = new Intent(context, UpdateService.class);
                serviceIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startService(serviceIntent);
            }
        }
    }

    private boolean autoUpdateCheck(Context context) {
        Log.d(TAG, "autoUpdateCheck start");
        String updateFilePath = SharePrefUtil.getString(context, SharePrefUtil.DOWNLOAD_FILE_PATH, "");
        if (updateFilePath == null || updateFilePath.length() == 0) {
            return false;
        }

        File file = new File(updateFilePath);
        if (!file.exists()) {
            return false;
        }

        Intent intent = new Intent(context, UpdateActivity.class);
        intent.putExtra("confirm", false);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
        Log.d(TAG, "autoUpdateCheck end");
        return true;
    }
}